#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>



#define KEY_OK_GPIO 32




void KeyGpioInit(unsigned int GPIO)
{
	unsigned char buf[100];
	sprintf(buf,"echo \"%d\" > /sys/class/gpio/export",GPIO);
	printf("%s\n",buf);
	system(buf);

	sprintf(buf,"echo \"in\" > /sys/class/gpio/gpio%d/direction",GPIO);
	printf("%s\n",buf);
	system(buf);
	
}

void KeyInit(void)
{
	KeyGpioInit(KEY_OK_GPIO);
}

static int gpio_read(int pin)  
{  
    char path[64];  
    char value_str[3];  
    int fd;  

    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", pin);  
    fd = open(path, 0);  //O_RDONLY=0

    if (fd < 0) {  
       printf("Failed to open gpio value for reading 1!\n");  
       return -1;  
    }  

    if (read(fd, value_str, 3) < 0) {  
       printf("Failed to read value!\n");  
       return -1;  
    }  

    close(fd);  
    return (atoi(value_str));
}  

int getKeyValue(void)
{
	int sta = 0;
	if (gpio_read(KEY_OK_GPIO) == 1)
	{
		sta = 1;
	}
	return sta;
}

void main(void)
{
    KeyInit();
    while(1)
    {
        printf("key=%d\n",getKeyValue());
        sleep(1);
    }
    
}